package com.lanhe.framework.web.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.core.domain.entity.LhMemberBase;
import com.lanhe.common.core.domain.entity.SysUser;
import com.lanhe.common.core.domain.model.LoginUser;
import com.lanhe.common.core.domain.wechat.WechatUser;
import com.lanhe.common.core.domain.wechat.WechatUserToken;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.DateUtils;
import com.lanhe.common.utils.wechat.WechatUtil;
import com.lanhe.common.utils.weixinUtils.WeiXinUtils;
import com.lanhe.common.utils.weixinUtils.vo.LoginCodeVo;
import com.lanhe.common.utils.weixinUtils.vo.WeiXinUserVo;
import com.lanhe.game.sysAppUser.domain.SysAppUser;
import com.lanhe.game.sysAppUser.mapper.SysAppUserMapper;
import com.lanhe.member.service.ILhMemberBaseService;
import com.lanhe.verifyRec.service.ILhVerifyRecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author lanhe
 */
@Component
public class AppLoginService {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private WechatUtil wechatUtil;

	@Autowired
	private WeiXinUtils weiXinUtils;
	@Autowired
	private SysAppUserMapper sysAppUserMapper;

	@Autowired
	public RedisTemplate redisTemplate;

	@Autowired
	private ILhMemberBaseService lhMemberBaseService;

	@Resource
	private ILhVerifyRecService lhVerifyRecService;//验证码


	/**
	 * app用户登录
	 * @param code
	 * @return
	 */

	public Map<String, Object> sysAppUserService(String code) {
		LoginCodeVo loginCodeVo = weiXinUtils.wechatLogin(code);
		System.err.println("loginCodeVo "+loginCodeVo);
		if (ObjectUtil.isNull(loginCodeVo)){
			throw  new ServiceException("获取微信失败，请稍后再试", HttpStatus.ERROR);
		}
		// 先看用户有没有注册登录
		SysAppUser sysAppUser = sysAppUserMapper.selectSysAppUserByOpenId(loginCodeVo.getOpenId());
		if (ObjectUtil.isNull(sysAppUser)){
			sysAppUser = new SysAppUser();
			// 还没有注册
			// 获取用户的登录信息
			WeiXinUserVo userInfo = weiXinUtils.getUserInfo(loginCodeVo);
			System.err.println("userInfo "+userInfo);
			// 添加app用户
			// 用redis生成自增id存入数据库中
			Long appUserId = redisTemplate.opsForValue().increment("appUserId");
			sysAppUser.setNickName(userInfo.getNickname());
			sysAppUser.setSex(userInfo.getSex()+"");
			sysAppUser.setOpenId(userInfo.getOpenId());
			sysAppUser.setHeadImgUrl(userInfo.getHeadImgUrl());
			sysAppUser.setCountry(userInfo.getCountry());
			sysAppUser.setProvince(userInfo.getProvince());
			sysAppUser.setCity(userInfo.getCity());
			sysAppUser.setAppUserId(appUserId);
			sysAppUser.setCreateTime(new Date());
			sysAppUser.setDelFlag("0");
			System.err.println("sysAppUser "+sysAppUser);
			sysAppUserMapper.insertSysAppUser(sysAppUser);
		}

		LoginUser loginUser = new LoginUser();
		loginUser.setUserId(sysAppUser.getAppUserId());
		loginUser.setUserOpenId(sysAppUser.getOpenId());

		SysUser sysUser = new SysUser();
		sysUser.setUserName(sysUser.getNickName());
		loginUser.setUser(sysUser);
		String token = tokenService.createGameAppToken(loginUser);

		Map<String, Object> result = new HashMap<>();
		result.put("token", token);
		result.put("id",loginCodeVo.getOpenId());
		result.put("code", 200);

		System.err.println("token "+token);
		return result;
	}



	public Map<String, Object> wechatLogin(String code) throws Exception {

		WechatUserToken wechatUserToken = wechatUtil.getAccessTokenBycode(code);
		if (ObjectUtil.isNull(wechatUserToken.getOpenId())) {
			throw new ServiceException("获取微信失败，请稍后再试", HttpStatus.ERROR);
		}
		LhMemberBase memberBase = lhMemberBaseService.getLhMemberBaseByWxId(wechatUserToken.getOpenId());
		if (Objects.isNull(memberBase)) {
			WechatUser wechatUser = wechatUtil.getUserInfo(wechatUserToken.getAccessToken(), wechatUserToken.getOpenId());
			LhMemberBase newMemberBase = createNewMemberBaseFromWechatUser(wechatUser);
			memberBase = lhMemberBaseService.addLhMemberBase(newMemberBase);
		} else {

			memberBase.setRecentLoginTime(DateUtils.getNowDate());
			lhMemberBaseService.updateLhMemberBase(memberBase);
		}

		LoginUser loginUser = new LoginUser();
		loginUser.setUserId(memberBase.getMemberId());
		loginUser.setUserKey(memberBase.getUserKey());
		String token = tokenService.createAppToken(loginUser);

		Map<String, Object> result = new HashMap<>();
		result.put("token", token);

		return result;
	}

	private LhMemberBase createNewMemberBaseFromWechatUser(WechatUser wechatUser) {
		LhMemberBase newMemberBase = new LhMemberBase();
		newMemberBase.setHeadPic(wechatUser.getHeadImgUrl());
		newMemberBase.setUserName(wechatUser.getNickname());
		newMemberBase.setMobile(null);
		newMemberBase.setSex(wechatUser.getSex());
		newMemberBase.setWxId(wechatUser.getOpenId());
		newMemberBase.setWxNo(wechatUser.getUnionId());
		return newMemberBase;
	}


	public Map<String, Object> setXianfenLogin(String mobile,String packageName, String code) {
		Map<String,Object> map = new HashMap<>();
		/*
		 *先查看主表单有没有当下手机号
		 */
		LhMemberBase userByMobile = lhMemberBaseService.getUserByMobile(mobile);
		if (ObjectUtil.isEmpty(userByMobile)){
			map.put("status","401");
			map.put("data","先下载主栈并注册");
			return map;
		}
		// 验证验证码是否正确
		Boolean validate = lhVerifyRecService.validate(mobile, code, Constants.GeneralIntType.ONE);
		if (!validate) {
			map.put("status","402");
			map.put("data","验证码不正确，请核对");
			return map;
		}
		// 判断sysAppUser内有没有这个手机号
		LambdaQueryWrapper<SysAppUser> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SysAppUser::getMobile,mobile);
		wrapper.eq(SysAppUser::getPackageName,packageName);
		wrapper.eq(SysAppUser::getDelFlag,Constants.GeneralIntType.ZERO);
		SysAppUser sysAppUser = sysAppUserMapper.selectOne(wrapper);

		/**
		 * 如果是第一次添加就新增到数据库中，否则就直接跳过
		 */
		if (ObjectUtil.isEmpty(sysAppUser)){
			// 用redis生成自增id存入数据库中
			Long appUserId = redisTemplate.opsForValue().increment("appUserId");
			// 先保存手机号
			sysAppUser = new SysAppUser();
			sysAppUser.setAppUserId(appUserId);
			sysAppUser.setMobile(mobile);
			sysAppUser.setPackageName(packageName);
			sysAppUser.setDelFlag("0");
			sysAppUser.setCreateTime(new Date());
			sysAppUser.setUpdateTime(new Date());
			sysAppUserMapper.insertSysAppUser(sysAppUser);
		}


		// 生成token并返回
		LoginUser loginUser = new LoginUser();
//		loginUser.setUserId(sysAppUser.getAppUserId());
		String token = tokenService.createGameAppToken(loginUser);
		map.put("status","200");
		map.put("userId",sysAppUser.getAppUserId());
		map.put("token",token);
		return map;
	}
}
